﻿using System.Linq;
using System.Web.Mvc;

using Kooboo.Commerce.Contexts.Products;
using Kooboo.Commerce.Contexts.Categories;
using Kooboo.Web.Mvc.Paging;

namespace Kooboo.Web.Controllers
{
    using Kooboo.Commerce;
    using Kooboo.Web.Mvc;
    using Kooboo.Commerce.Services;
    using Kooboo.Web.Models;

    public class SearchController : ControllerBase
    {
        //
        // GET: /Search/

        public ActionResult Index(int? category, string query, int? page, string sort)
        {
            this.BindViewData();

            this.ViewBag.Breadcrumb = new object[] { };

            var searchService = new SearchService();

            var products = searchService.Search(category, query, sort).Select(i => new SearchResultProduct
            {
                Name = i.Name,
                Price = i.Price.ToString("C"),
                ProductUrl = this.Url.Action<ProductController>(m => m.View(i.ProductId, null)),
                Thumbnail = combianThumbnailImageUrl(i.Thumbnail)
            });

            return View(products.ToPagedList(page ?? 1, Configuration.PageSize));
        }

        private string combianThumbnailImageUrl(string thumbnailName)
        {
            if (!string.IsNullOrEmpty(thumbnailName))
            {
                return Kooboo.Commerce.Configuration.FindImageUrlBase(Kooboo.Commerce.Configuration.ProductImageFolder, "Thumnail")
                    + thumbnailName;
            }
            else
            {
                return Configuration.ImageNotAvailable_Thumbnail;
            }
        }
    }
}
